package nuaa.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 获取SqlSession对象
 */
public class UtilSqlSession {

    //输入流，承载SqlMapConfig.xml文件
    private static InputStream in;

    static {
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取Session
    private static SqlSession sqlSession=new SqlSessionFactoryBuilder().build(in).openSession();

    /**
     * 获取SqlSession
     * @return
     * @throws IOException
     */
    public static SqlSession getSqlSession() throws IOException {
        /*//创建工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //获取session
        sqlSession = factory.openSession();*/
        //返回sqlSession
        return sqlSession;
    }

    /**
     * 销毁链接
     * @throws IOException
     */
    public static void destroySqlSession() throws IOException {
        sqlSession.close();
        in.close();
    }
}
